<template>
  <div class="upload-container">
    <el-row>
      <el-col :span="24">
        <el-upload
          ref="upload"
          class="upload-demo"
          drag
          action="#"
          accept=".*"
          list-type="text"
          :http-request="uploadFile"
          :on-change="fileChange"
          :show-file-list="false"
          multiple
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-col>
      <el-col :span="24">
        <div v-for="(item, index) in files" :key="index" class="file-item pr mr20 fl">
          <img :src="item.url" class="file-item-img pr"/>
          <div class="file-item-name pa b0" :title="item.file_name" :href="item.url" target="_blank">{{ item.file_name }}</div>
          <div class="el-icon-circle-close pa file-close" @click="fileDel(index)" />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { uploadFile } from '@/api/file/cos'

export default {
  name: '',
  props: {
    value: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      files: []
    }
  },
  watch: {
    files: {
      handler(n, o) {
        this.emitInput()
      },
      deep: true
    },
    'value': {
      handler(n, o) {
        if(this.value && this.value !== '')this.$set(this, 'files', JSON.parse(this.value))
      },
      immediate: false
    }
  },
  created() {
    if(this.value && this.value !== '')this.$set(this, 'files', JSON.parse(this.value))
    // this.$set(this, 'files', JSON.parse("[{url: 'https://upload.liouhuanbao.com/file/20230926/608003794260996096/1695714744268/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg', file_name: 'test'},{url: 'https://upload.liouhuanbao.com/file/20230926/608003794260996096/1695714744268/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg', file_name: 'test'}]"))
  },
  methods: {
    uploadFile(param) {
      const formData = new FormData()
      formData.append('files', param.file)
      uploadFile(formData).then(res => {
        this.files.push(res.files[0])
        this.$message.success('上传成功')
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    fileDel(e) {
      this.files.splice(e, 1)
    },
    fileChange() {
      this.$refs.upload.clearFiles()
    },
    emitInput() {
      if (this.files.length === 0) {
        this.$emit('input', '[]')
      } else {
        this.$emit('input', JSON.stringify(this.files))
      }
    },
    beforeUpload() {
    }
  }
}
</script>

<style scoped>
.file-item{
  overflow: hidden;
  width: 100px;
  height: 120px;
}
.file-item:hover{
  background-color: #F5F7FA;
}
.file-close{
  right: 6px;
  top: 6px;
  cursor: pointer;
  width: 14px;
  height: 14px;

}
.file-item-img{
  width: 100px;
  height: 100px;
}
.file-item-name{
  text-align: center;
  height: 20px;
  line-height: 20px;
  width: 100%;
}
</style>
